package com.chinasoft.goodsManager.dao.impl;

import com.chinasoft.goodsManager.dao.OrderDao;
import com.chinasoft.goodsManager.doamain.Order;
import com.chinasoft.goodsManager.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class OrderDaoImpl implements OrderDao {
    JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<Order> findAll() {
        try {
            String sql = "select * from g_orders";
            return template.query(sql, new BeanPropertyRowMapper<>(Order.class));
        } catch (DataAccessException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean del(String str) {
        try {
            String sql = "delete from g_orders where id = ?";
            int update = template.update(sql, str);
            if (update != 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean add(Order order) {
        String sql = "insert into g_orders values (?,?,?,?,?,?,?,?)";
        int i = template.update(sql, null, order.getOdate(), order.getPname(), order.getPrice(), order.getAddress(), order.getNum(), order.getOprice(), order.getCategory());
        if (i != 0)
            return true;
        else
            return false;
    }

    @Override
    public List<Order> find(String str) {
        try {
            String sql = "select * from g_orders where id = ?";
            return template.query(sql, new BeanPropertyRowMapper<>(Order.class),str);
        } catch (DataAccessException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean update(Order order) {
        String sql = "update g_orders set odate = ?,Pname = ?,price = ?,address = ?,num = ?,Oprice = ?,category = ? where id = ?";
        System.out.println(order);
        int i = template.update(sql, order.getOdate(), order.getPname(), order.getPrice(), order.getAddress(),order.getNum(),order.getOprice(),order.getCategory(),order.getId());
        System.out.println(i);
        if (i != 0)
            return true;
        else
            return false;
    }
}
